// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#include "coin2/exchange/btcturk/api_util/rate_tracker.h"

#include <algorithm>
#include <sstream>
#include <string>

#include <boost/algorithm/string/replace.hpp>
#include <glog/logging.h>

#include "coin2/base/proto_util.h"
#include "coin2/exchange/base/order/rate_config.h"

namespace coin2::exchange::btcturk::api_util {

constexpr auto EXAMPLE_SPOT_BTCTURK = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke18/btcturk/trade_key.json",
  "rate_limit_info": {
    "spot_btcturk": {
      "all": {
        "secs": 60,
        "reqs": 600
      },
      "balance": {
        "secs": 60,
        "reqs": 90
      },
      "order_min": {
        "secs": 60,
        "reqs": 300
      },
      "order_sec": {
        "secs": 1,
        "reqs": 10
      },
      "trade": {
        "secs": 60,
        "reqs": 90
      }
    }
  }
},)";

template <class RateTracker>
void CheckFail(RateTracker&& rate_tracker, bool check_result) {
  if (!check_result) {
    LOG(INFO) << "Hit rate limit on [" << rate_tracker->GetName() << "]";
  }
}

BtcturkRateTracker::BtcturkRateTracker(
    const MarketExchangeApi& mea,
    const coin2::exchange::order::OrderConnectionConfig& cfg) {
  using RateConfig = coin2::exchange::base::order::RateConfig;
  if (mea.market == coin::proto::MarketType::Spot) {
    RateLimitInfoSpotBtcturk rate_config;
    RateConfig::Get()->GetConfig(mea, cfg, &rate_config);
    InitRateTracker(&rate_config, mea.String(), EXAMPLE_SPOT_BTCTURK);
  } else {
    CHECK(false) << "unsupported mea: " << mea.String();
  }
}

void BtcturkRateTracker::InitRateTracker(
    RateLimitInfoSpotBtcturk* rate_config,
    std::string_view mea_str,
    std::string_view example) {
  if (!rate_config || !rate_config->has_all() || !rate_config->has_balance() ||
      !rate_config->has_order_min() || !rate_config->has_order_sec() || !rate_config->has_trade()) {
    coin2::exchange::base::order::RateConfig::CheckFail(mea_str, example);
  }
  const auto& all = rate_config->all();
  const auto& balance = rate_config->balance();
  const auto& order_min = rate_config->order_min();
  const auto& order_sec = rate_config->order_sec();
  const auto& trade = rate_config->trade();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\nall: [" << all.reqs() << "(reqs)/" << all.secs() << "(seconds)]"
            << "\nbalance: [" << balance.reqs() << "(reqs)/" << balance.secs() << "(seconds)]"
            << "\norder_min: [" << order_min.reqs() << "(reqs)/" << order_min.secs() << "(seconds)]"
            << "\norder_sec: [" << order_sec.reqs() << "(reqs)/" << order_sec.secs() << "(seconds)]"
            << "\ntrade: [" << trade.reqs() << "(reqs)/" << trade.secs() << "(seconds)]"
            << "\n\nOr you can configure customized rate in driver config. For example: " << example
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

  rate_tracker_all_ = std::make_unique<FixedWindowRateTracker>(all.secs() * 1'000'000'000LL);
  rate_tracker_all_->SetRateLimitInfo(all.reqs(), all.reqs());
  rate_tracker_all_->SetName("btcturk_rate_tracker_all(1 min)");

  rate_tracker_balance_ =
      std::make_unique<FixedWindowRateTracker>(balance.secs() * 1'000'000'000LL);
  rate_tracker_balance_->SetRateLimitInfo(balance.reqs(), balance.reqs());
  rate_tracker_balance_->SetName("btcturk_rate_tracker_balance(1 min)");

  rate_tracker_openorder_ =
      std::make_unique<FixedWindowRateTracker>(order_min.secs() * 1'000'000'000LL);
  rate_tracker_openorder_->SetRateLimitInfo(order_min.reqs(), order_min.reqs());
  rate_tracker_openorder_->SetName("btcturk_rate_tracker_order(1 min)");

  rate_tracker_historder_ =
      std::make_unique<FixedWindowRateTracker>(order_min.secs() * 1'000'000'000LL);
  rate_tracker_historder_->SetRateLimitInfo(order_min.reqs(), order_min.reqs());
  rate_tracker_historder_->SetName("btcturk_rate_tracker_order(1 min)");

  rate_tracker_placeorder_min_ =
      std::make_unique<FixedWindowRateTracker>(order_min.secs() * 1'000'000'000LL);
  rate_tracker_placeorder_min_->SetRateLimitInfo(order_min.reqs(), order_min.reqs());
  rate_tracker_placeorder_min_->SetName("btcturk_rate_tracker_order(1 min)");

  rate_tracker_placeorder_sec_ =
      std::make_unique<FixedWindowRateTracker>(order_sec.secs() * 1'000'000'000LL);
  rate_tracker_placeorder_sec_->SetRateLimitInfo(order_sec.reqs(), order_sec.reqs());
  rate_tracker_placeorder_sec_->SetName("btcturk_rate_tracker_order(1 sec)");

  rate_tracker_cancelorder_min_ =
      std::make_unique<FixedWindowRateTracker>(order_min.secs() * 1'000'000'000LL);
  rate_tracker_cancelorder_min_->SetRateLimitInfo(order_min.reqs(), order_min.reqs());
  rate_tracker_cancelorder_min_->SetName("btcturk_rate_tracker_order(1 min)");

  rate_tracker_cancelorder_sec_ =
      std::make_unique<FixedWindowRateTracker>(order_sec.secs() * 1'000'000'000LL);
  rate_tracker_cancelorder_sec_->SetRateLimitInfo(order_sec.reqs(), order_sec.reqs());
  rate_tracker_cancelorder_sec_->SetName("btcturk_rate_tracker_order(1 sec)");

  rate_tracker_fillorder_ =
      std::make_unique<FixedWindowRateTracker>(trade.secs() * 1'000'000'000LL);
  rate_tracker_fillorder_->SetRateLimitInfo(trade.reqs(), trade.reqs());
  rate_tracker_fillorder_->SetName("btcturk_rate_tracker_trade(1 min)");

  rate_limit_report_writer_ = std::make_unique<RateLimitReportWriter>();
  rate_limit_report_writer_->SetRateLimitInfoString(rate_config);
}

bool BtcturkRateTracker::HasEnoughRateLimit(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (CheckEnableTime(timestamp, action_type, query_type) &&
      CheckRateLimit(timestamp, action_type, query_type)) {
    return true;
  }

  rate_limit_report_writer_->SetHitRateLimit(timestamp, action_type);
  return false;
}

void BtcturkRateTracker::Push(
    int32_t num_reqs,
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_min_) {
      rate_tracker_placeorder_min_->Push(num_reqs, timestamp);
    }
    if (rate_tracker_placeorder_sec_) {
      rate_tracker_placeorder_sec_->Push(num_reqs, timestamp);
    }
  } else if (action_type == ActionType::CANCEL) {
    if (rate_tracker_cancelorder_min_) {
      rate_tracker_cancelorder_min_->Push(num_reqs, timestamp);
    }
    if (rate_tracker_cancelorder_sec_) {
      rate_tracker_cancelorder_sec_->Push(num_reqs, timestamp);
    }
  } else if (action_type == ActionType::QUERY) {
    if (query_type == QueryType::BALANCE) {
      if (rate_tracker_balance_) {
        rate_tracker_balance_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::OPEN_ORDER) {
      if (rate_tracker_openorder_) {
        rate_tracker_openorder_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::HIST_ORDER) {
      if (rate_tracker_historder_) {
        rate_tracker_historder_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::FILL_ORDER) {
      if (rate_tracker_fillorder_) {
        rate_tracker_fillorder_->Push(num_reqs, timestamp);
      }
    } else {
      return;
    }
  } else {
    return;
  }

  if (rate_tracker_all_) {
    rate_tracker_all_->Push(num_reqs, timestamp);
  }
}

void BtcturkRateTracker::SetRateLimitInfoString(const google::protobuf::Message* message) {
  if (!rate_limit_report_writer_) {
    return;
  }
  rate_limit_report_writer_->SetRateLimitInfoString(message);
}

void BtcturkRateTracker::WriteRateLimitReportMessage(OrderLoggerCB callback) {
  if (!callback) {
    return;
  }
  rate_limit_report_writer_->Write(callback);
}

double BtcturkRateTracker::GetMaxRateUsedRatio(int64_t timestamp, ActionType action_type) {
  switch (action_type) {
    case ActionType::PLACE: {
      return std::max(
          GetMaxRateUsedRatio(rate_tracker_placeorder_min_, timestamp),
          GetMaxRateUsedRatio(rate_tracker_placeorder_sec_, timestamp));
    }
    case ActionType::CANCEL: {
      return std::max(
          GetMaxRateUsedRatio(rate_tracker_cancelorder_min_, timestamp),
          GetMaxRateUsedRatio(rate_tracker_cancelorder_sec_, timestamp));
    }
    case ActionType::QUERY: {
      double balance_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_balance_, timestamp);
      double openorder_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_openorder_, timestamp);
      double historder_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_historder_, timestamp);
      double fillorder_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_fillorder_, timestamp);
      return std::max(
          std::max(balance_rate_used_ratios, openorder_rate_used_ratios),
          std::max(historder_rate_used_ratios, fillorder_rate_used_ratios));
    }
    default: {
      // shouldn't reached here
      LOG(ERROR) << "ops~ something is wrong, action_type=" << action_type;
      return 0.;
    }
  }
}

bool BtcturkRateTracker::CheckEnableTime(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (timestamp >= enable_time_) {
    return true;
  }

  LOG_EVERY_N(WARNING, 50) << "Hit api temporary disabled until " << enable_time_ << ", "
                           << action_type << ", " << query_type;
  return false;
}

bool BtcturkRateTracker::CheckRateLimit(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  bool ret = true;
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_min_) {
      ret = rate_tracker_placeorder_min_->GetRemaining(timestamp) > 2;
      CheckFail(rate_tracker_placeorder_min_, ret);
    }
    if (rate_tracker_placeorder_sec_) {
      ret = rate_tracker_placeorder_sec_->GetRemaining(timestamp) > 1;
      CheckFail(rate_tracker_placeorder_sec_, ret);
    }
  } else if (action_type == ActionType::CANCEL) {
    if (rate_tracker_cancelorder_min_) {
      ret = rate_tracker_cancelorder_min_->GetRemaining(timestamp) > 2;
      CheckFail(rate_tracker_cancelorder_min_, ret);
    }
    if (rate_tracker_cancelorder_sec_) {
      ret = rate_tracker_cancelorder_sec_->GetRemaining(timestamp) > 1;
      CheckFail(rate_tracker_cancelorder_sec_, ret);
    }
  } else if (action_type == ActionType::QUERY) {
    if (query_type == QueryType::BALANCE) {
      if (rate_tracker_balance_) {
        ret = (rate_tracker_balance_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_balance_, ret);
      }
    } else if (query_type == QueryType::OPEN_ORDER) {
      if (rate_tracker_openorder_) {
        ret = (rate_tracker_openorder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_openorder_, ret);
      }
    } else if (query_type == QueryType::HIST_ORDER) {
      if (rate_tracker_historder_) {
        ret = (rate_tracker_historder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_historder_, ret);
      }
    } else if (query_type == QueryType::FILL_ORDER) {
      if (rate_tracker_fillorder_) {
        ret = (rate_tracker_fillorder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_fillorder_, ret);
      }
    }
  }
  if (rate_tracker_all_) {
    ret &= (rate_tracker_all_->GetRemaining(timestamp) > 2);
    CheckFail(rate_tracker_all_, ret);
  }

  return ret;
}
}  // namespace coin2::exchange::btcturk::api_util
